package xyz.syyrjx.registry.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.syyrjx.client.SyyrjxRpcClient;
import xyz.syyrjx.initializer.SyyrjxRpcChannelInitializer;
import xyz.syyrjx.registry.conf.SyyrjxRpcRegistryConfiguration;
import xyz.syyrjx.registry.handler.SyyrjxRpcRegistryClientHandler;

import java.util.*;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author 大地崩坏苍蝇兽
 * @date 2023/1/16 - 19:45
 */
public class SyyrjxRpcRegistryReconncetSchedule {
    private final static Logger LOGGER = LoggerFactory.getLogger(SyyrjxRpcRegistryReconncetSchedule.class);

    private final static Set<SyyrjxRpcClient> CONNECT_FAIL_CLIENT_SET = new CopyOnWriteArraySet<>();

    private static volatile boolean run = false;


    public static void addClient(SyyrjxRpcClient client) {
        CONNECT_FAIL_CLIENT_SET.add(client);
    }

    public static int countFailClient(){
        return CONNECT_FAIL_CLIENT_SET.size();
    }

    public static void reconncetStart(SyyrjxRpcClient client) {
        addClient(client);
        reconncetStart();
    }

    public static void reconncetStart() {
        //没有被运行才能跑
        if (!SyyrjxRpcRegistryReconncetSchedule.run) {
            SyyrjxRpcRegistryReconncetSchedule.run = true;
            Timer timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    //连接失败客户端集合中没有客户端对象，表示全部客户端都连接成功，取消重试定时任务
                    if (CONNECT_FAIL_CLIENT_SET.size() == 0) {
                        LOGGER.debug("已经没有连接失败的任务");
                        timer.cancel();
                        //表示任务不再运行了
                        SyyrjxRpcRegistryReconncetSchedule.run = false;
                    } else {
                        for (SyyrjxRpcClient client : CONNECT_FAIL_CLIENT_SET) {
                            LOGGER.debug("重试" + client);
                            try {
                                //本注册中心客户端连接远程注册中心
                                SyyrjxRpcChannelInitializer channelInitializer = new SyyrjxRpcChannelInitializer();
                                SyyrjxRpcRegistryClientHandler handler = new SyyrjxRpcRegistryClientHandler();
                                channelInitializer.setMaxReadSize(SyyrjxRpcRegistryConfiguration
                                        .getConfiguration().getMaxReadSize());
                                channelInitializer.setHandler(handler);
                                client.run(channelInitializer);
                                if (client.getChannel().isActive()) {
                                    //连接成功，从连接失败客户端集合中删除并加入同步任务客户端集合中
                                    CONNECT_FAIL_CLIENT_SET.remove(client);
                                    SyyrjxRpcRegistrySynchronizeTask.addClient(client);
                                    LOGGER.debug("重试" + client + "成功");
                                    LOGGER.debug("删除" + client);
                                    LOGGER.debug("当前未连接成功的客户端有" + CONNECT_FAIL_CLIENT_SET.size() + "个："
                                            + CONNECT_FAIL_CLIENT_SET);
                                }
                            } catch (Exception e) {
                                LOGGER.debug("重试" + client + "失败");
                            }
                        }
                    }
                }
            };
            timer.schedule(task, 0, 5000);
        }
    }


}
